package com.spic.business.hidden.governance.service.impl;

import com.spic.business.common.core.workflow.IWorkFlowType;
import com.spic.business.common.datascope.anotation.BusinessDataScope;
import com.spic.business.common.workflow.WorkFlowServiceImpl;
import com.spic.business.enumconst.BusinessType;
import com.spic.business.hidden.governance.domain.HiddenGovernance;
import com.spic.business.hidden.governance.domain.vo.HiddenStandingVo;
import com.spic.business.hidden.governance.mapper.HiddenGovernanceMapper;
import com.spic.business.hidden.governance.service.IHiddenGovernanceService;
import com.spic.common.core.utils.DateUtils;
import com.spic.common.core.utils.SecurityUtils;
import com.spic.common.core.utils.StringUtils;
import com.spic.system.api.RemoteDeptService;
import com.spic.system.api.RemoteNoticeInfoService;
import com.spic.system.api.domain.BusinessStatus;
import com.spic.system.api.domain.SysNoticeInfo;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 隐患排查治理Service业务层处理
 *
 * @author renxiang
 * @date 2021-10-15
 */
@Service
public class HiddenGovernanceServiceImpl extends WorkFlowServiceImpl<HiddenGovernanceMapper, HiddenGovernance> implements IHiddenGovernanceService
{
    @Autowired
    private HiddenGovernanceMapper hiddenGovernanceMapper;
    @Autowired
    private RemoteNoticeInfoService remoteNoticeInfoService;
    @Autowired
    private RemoteDeptService remoteDeptService;
    /**
     * 查询隐患排查治理
     *
     * @param id 隐患排查治理主键
     * @return 隐患排查治理
     */
    @Override
    public HiddenGovernance selectHiddenGovernanceById(Integer id)
    {
        return hiddenGovernanceMapper.selectHiddenGovernanceById(id);
    }
    /**
     * 查询隐患排查治理列表
     *
     * @param hiddenGovernance 隐患排查治理
     * @return 隐患排查治理
     */
    @Override
    @BusinessDataScope(menuPath = "business/hidden/hidden_governance/index")
    public List<HiddenGovernance> selectHiddenGovernanceList(HiddenGovernance hiddenGovernance)
    {
        List<HiddenGovernance> hiddenGovernancesList = hiddenGovernanceMapper.selectHiddenGovernanceList(hiddenGovernance);
        if(StringUtils.isNotNull(hiddenGovernancesList) && hiddenGovernancesList.size()>0){
            processRow(hiddenGovernancesList, this::row);
        }
        return hiddenGovernancesList;
    }

    //处理每条业务自己逻辑
    private void row(HiddenGovernance hidden){
    }
    /**
     * 新增隐患排查治理
     *
     * @param hiddenGovernance 隐患排查治理
     * @return 结果
     */
    @Override
    public Long insertHiddenGovernance(HiddenGovernance hiddenGovernance)
    {
        hiddenGovernance.setCreateTime(DateUtils.getNowDate());
        hiddenGovernanceMapper.insertHiddenGovernance(hiddenGovernance);
        return hiddenGovernance.getId();
    }

    /**
     * 修改隐患排查治理
     *
     * @param hiddenGovernance 隐患排查治理
     * @return 结果
     */
    @Override
    public int updateHiddenGovernance(HiddenGovernance hiddenGovernance)
    {
        hiddenGovernance.setUpdateTime(DateUtils.getNowDate());
        return hiddenGovernanceMapper.updateHiddenGovernance(hiddenGovernance);
    }

    /**
     * 批量删除隐患排查治理
     *
     * @param ids 需要删除的隐患排查治理主键
     * @return 结果
     */
    @Override
    public int deleteHiddenGovernanceByIds(Integer[] ids)
    {
        return hiddenGovernanceMapper.deleteHiddenGovernanceByIds(ids);
    }

    /**
     * 删除隐患排查治理信息
     *
     * @param id 隐患排查治理主键
     * @return 结果
     */
    @Override
    public int deleteHiddenGovernanceById(Integer id)
    {
        return hiddenGovernanceMapper.deleteHiddenGovernanceById(id);
    }

    @Override
    public void deadlineMessage()
    {
        List<HiddenGovernance> hiddenGovernances = hiddenGovernanceMapper.selectHiddenGovernanceList(null);
        Map<String, BusinessStatus> statusMap = getWorkFlowStatus(hiddenGovernances);
        if(hiddenGovernances!=null &&  hiddenGovernances.size()>0){
            for (HiddenGovernance hiddenGovernance : hiddenGovernances)
            {
                BusinessStatus businessStatus = statusMap.get(hiddenGovernance.getId());
                if(businessStatus.getStatus()==3){
                    continue;
                }
                String rectificationType = hiddenGovernance.getRectificationType();
                if(StringUtils.isNotEmpty(rectificationType)){
                    if(rectificationType.equals("01")){
                        Date rectificationPeriod = hiddenGovernance.getRectificationPeriod();
                        if(rectificationPeriod.getTime()<=new Date().getTime()){
                            SysNoticeInfo sysNoticeInfo = new SysNoticeInfo();
                            sysNoticeInfo.setContent("你有代办未办理");
                            sysNoticeInfo.setTitle("你有代办未办理，请及时处理");
                            //TODO
//                            sysNoticeInfo.setUserId(userId);
                            remoteNoticeInfoService.add(sysNoticeInfo);
                        }
                    }
                }
            }
        }
    }

    @Override
    public List<Map<String, Object>> getWeekHidden()
    {
        List<HiddenGovernance> hiddenGovernanceList = hiddenGovernanceMapper.selectHiddenGovernanceByWeek();
        List<Map<String, Object>> listMap = new ArrayList<>();

        List<String> monthFullDay = getMonthFullDay(new Date());
        Collections.sort(monthFullDay);
        for (String weekDay : monthFullDay)
        {
            Map<String, Object> m = new HashMap<>();
            m.put("day",weekDay);
            List<String> listC = new ArrayList<>();
            List<String> listR = new ArrayList<>();

            for (HiddenGovernance hiddenGovernance : hiddenGovernanceList)
            {

                String hazardStatus = hiddenGovernance.getHazardStatus(); //隐患状态
                Date createTime = hiddenGovernance.getCreateTime(); //创建时间
                String createTimeDay = DateFormatUtils.format(createTime, "yyyy-MM-dd");
                if(weekDay.equals(createTimeDay)){ //隐患数据
                    listC.add(hiddenGovernance.getId()+"");
                }

                Date acceptanceTime = hiddenGovernance.getAcceptanceTime(); //整改时间
                if(StringUtils.isNotNull(acceptanceTime)){
                    String acceptanceTimeDay = DateFormatUtils.format(acceptanceTime, "yyyy-MM-dd");
                    if(weekDay.equals(acceptanceTimeDay)){ //整改数据
                        listR.add(hiddenGovernance.getId()+"");
                    }
                }
            }
            //聚合数据
            listC.removeAll(listR);
            m.put("hiddenCheck",listC.size()); //隐患排查数量
            m.put("hiddenRectification",listR.size()); //隐患整改数量
            listMap.add(m);
        }

        return listMap;
    }

    public static List<String> getMonthFullDay(Date date){
        String yyyy = DateFormatUtils.format(date, "yyyy");
        String mm = DateFormatUtils.format(date, "MM");
        String dd = DateFormatUtils.format(date, "dd");

        SimpleDateFormat dateFormatYYYYMMDD = new SimpleDateFormat("yyyy-MM-dd");
        List<String> fullDayList = new ArrayList<>(32);
        // 获得当前日期对象
        Calendar cal = Calendar.getInstance();
        cal.clear();// 清除信息
        cal.set(Calendar.YEAR, Integer.parseInt(yyyy));
        // 1月从0开始
        cal.set(Calendar.MONTH, Integer.parseInt(mm)-1 );
        // 当月1号
        cal.set(Calendar.DAY_OF_MONTH,Integer.parseInt(dd));
        int count = cal.getActualMaximum(7);
        for (int j = 1; j <= count ; j++) {
            fullDayList.add(dateFormatYYYYMMDD.format(cal.getTime()));
            cal.add(Calendar.DAY_OF_MONTH,-1);
        }
        return fullDayList;
    }
    @Override
    protected IWorkFlowType getWorkFlowType()
    {
        return BusinessType.HIDDEN_GOVERNANCE;
    }

    @Override
    protected void setWorkFlowVariable(HiddenGovernance entity, Map<String, Object> variable)
    {
        variable.put("drafter", SecurityUtils.getUserId());
        variable.put("rectification", entity.getRectificationPeople());
    }

    @Override
    public List<HiddenStandingVo> selectHiddenStandingList(HiddenStandingVo hiddenStandingVo)
    {
        List<HiddenStandingVo> hiddenStandingVoList = new ArrayList<>();
        Long deptId = hiddenStandingVo.getDeptId();
        HiddenGovernance h = new HiddenGovernance();

        if(StringUtils.isNotNull(deptId)){
            h.setRectificationDept(deptId+"");
        }
        List<HiddenGovernance> hiddenGovernancesList = hiddenGovernanceMapper.selectHiddenGovernanceByYearList(h);
        if(StringUtils.isNotNull(hiddenGovernancesList) && hiddenGovernancesList.size()>0){
            processRow(hiddenGovernancesList, this::row);
        }
        Map<String, List<HiddenGovernance>> collect = hiddenGovernancesList.stream().filter(s -> Objects.nonNull(s.getRectificationDept())).collect(Collectors.groupingBy(HiddenGovernance::getRectificationDept));

        Set<String> deptKeySet = collect.keySet();
        for(Iterator<String> it = deptKeySet.iterator();it.hasNext();) {

            String kdept = it.next();
            List<HiddenGovernance> deptHidden = collect.get(kdept);
            String deptName = remoteDeptService.getDeptName(Long.valueOf(kdept)).getData();
            String parentDeptName = remoteDeptService.getSysDeptBychildenId(Long.valueOf(kdept)).getMsg();

            List<HiddenGovernance> hiddenGovernanceList=  collect.get(kdept);
            Map<String, List<HiddenGovernance>> collectList = hiddenGovernanceList.stream().filter(s -> Objects.nonNull(s.getYear())).collect(Collectors.groupingBy(HiddenGovernance::getYear));

            Set<String> yearKeys = collectList.keySet();
            for(Iterator<String> yearIts = yearKeys.iterator();yearIts.hasNext();)
            {
                String yearKey = yearIts.next();
                List<HiddenGovernance> hidden = collectList.get(yearKey);
                Map<String, List<HiddenGovernance>> collectYear = hidden.stream().filter(s -> Objects.nonNull(s.getMonth())).collect(Collectors.groupingBy(HiddenGovernance::getMonth));
                Set<String> monthKeys = collectYear.keySet();
                for(Iterator<String> monthIts = monthKeys.iterator();monthIts.hasNext();)
                {
                    String monthKey = monthIts.next();
                    List<HiddenGovernance> monthHidden = collectYear.get(monthKey);
                    HiddenStandingVo hi = new HiddenStandingVo();
                    if(StringUtils.isNotEmpty(parentDeptName)){
                        hi.setDeptName(parentDeptName+"-"+deptName);

                    } else{
                        hi.setDeptName(deptName);
                    }
                    hi.setDeptId(Long.valueOf(kdept));
                    hi.setYear(yearKey);
                    hi.setMouth(monthKey);
                    hi.setHiddenGovernanceList(monthHidden);
                    hi.setFileName(hi.getDeptName()+yearKey+"年"+monthKey+"月隐患排查台账");
                    hiddenStandingVoList.add(hi);
                }


            }
        }
        List<HiddenStandingVo> hiddenStandingVoListSort = hiddenStandingVoList.stream().sorted(Comparator.comparing(HiddenStandingVo::getYear,Comparator.reverseOrder()).thenComparing(HiddenStandingVo::getMouth,Comparator.reverseOrder())).collect(Collectors.toList());
        return hiddenStandingVoListSort;
    }
}
